package com.ui.service.Impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wanmei.util.OrderIDUtil;
import com.wanmei.mapper.OrderdetailMapper;
import com.wanmei.mapper.OrderProductMapper;
import com.wanmei.pojo.CartItem;
import com.wanmei.pojo.Orderdetail;
import com.wanmei.pojo.OrderProduct;
import com.ui.service.OrderProductService;

@Service
public class OrderProductServiceImpl implements OrderProductService {
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private OrderdetailMapper orderDetailMapper;
	
	public String insert(List<CartItem> item) {
		// TODO Auto-generated method stub
		//生成订单号
		String orderKey=OrderIDUtil.orderKeyGenerator();
		//计算总数量
		int num=item.stream().mapToInt(CartItem::getNum).sum();
		//计算总价格	
		Optional<Float> price = item.stream().map(x->x.getNum()*x.getProduct().getPrice()).reduce(Float::sum);
		
		OrderProduct order = new OrderProduct();
		order.setOid(orderKey);
		order.setTotal(13000.0);//总金额 Double.valueOf(price.get())
		order.setProductnum(num);//总数量
		order.setOstate(1);//1、新建 2、核对账单   3、待付款  4、已支付   
		int i=orderProductMapper.insert(order);
		
		for(CartItem cartItem : item) {
			Orderdetail detail=new Orderdetail();
			detail.setOid(orderKey);
			detail.setPid(cartItem.getId());
			detail.setPkuid(cartItem.getKuid());
			detail.setProductname(cartItem.getProduct().getPname());
			detail.setProductnum(cartItem.getNum());
			detail.setProductprice(cartItem.getProduct().getPrice());
			detail.setAttrvalue(cartItem.getvAttrValue());
			orderDetailMapper.insert(detail);
		}
		return orderKey;
	}


	@Override
	public OrderProduct selectByOid(String oid) {
		return orderProductMapper.selectByOid(oid);
	}
}
